import axios from 'axios';
import { mockBackendAPI } from './mockBackend';

// 微信开发者平台配置
const WECHAT_APP_ID = 'wxc0c160e79453964e';
const WECHAT_REDIRECT_URI = encodeURIComponent(window.location.origin + '/wechat-callback');

// 微信登录状态枚举
export enum WechatLoginStatus {
  WAITING = 'waiting',
  SCANNED = 'scanned',
  CONFIRMED = 'confirmed',
  EXPIRED = 'expired',
  ERROR = 'error'
}

// 微信登录结果接口
export interface WechatLoginResult {
  status: WechatLoginStatus;
  message: string;
  userInfo?: {
    openid: string;
    nickname: string;
    headimgurl: string;
    unionid?: string;
  };
  accessToken?: string;
}

// 生成微信登录二维码
export const generateWechatQRCode = async (): Promise<string> => {
  try {
    // 构建微信授权URL - 修复scope参数
    const authUrl = `https://open.weixin.qq.com/connect/qrconnect?appid=${WECHAT_APP_ID}&redirect_uri=${WECHAT_REDIRECT_URI}&response_type=code&scope=snsapi_userinfo&state=${Date.now()}#wechat_redirect`;
    
    // 使用qrcode.react生成二维码
    return authUrl;
  } catch (error) {
    console.error('生成微信二维码失败:', error);
    throw new Error('生成二维码失败');
  }
};

// 检查微信登录状态
export const checkWechatLoginStatus = async (state: string): Promise<WechatLoginResult> => {
  try {
    // 使用模拟后端API
    const result = await mockBackendAPI.checkLoginStatus(state);
    return result;
  } catch (error) {
    console.error('检查登录状态失败:', error);
    return {
      status: WechatLoginStatus.ERROR,
      message: '检查状态失败，请重试'
    };
  }
};



// 处理微信回调
export const handleWechatCallback = async (code: string, state: string): Promise<WechatLoginResult> => {
  try {
    // 使用模拟后端API
    const result = await mockBackendAPI.handleCallback(code, state);
    return result;
  } catch (error) {
    console.error('处理微信回调失败:', error);
    throw new Error('登录失败');
  }
};

// 微信用户信息接口
export interface WechatUserInfo {
  openid: string;
  nickname: string;
  headimgurl: string;
  unionid?: string;
  sex?: number;
  city?: string;
  province?: string;
  country?: string;
}

// 微信令牌刷新结果接口
export interface WechatTokenResult {
  access_token: string;
  refresh_token: string;
  openid: string;
  scope: string;
  expires_in: number;
}

// 获取微信用户信息
export const getWechatUserInfo = async (accessToken: string, openid: string): Promise<WechatUserInfo> => {
  try {
    const response = await axios.get(`https://api.weixin.qq.com/sns/userinfo?access_token=${accessToken}&openid=${openid}&lang=zh_CN`);
    return response.data;
  } catch (error) {
    console.error('获取微信用户信息失败:', error);
    throw new Error('获取用户信息失败');
  }
};

// 刷新微信访问令牌
export const refreshWechatToken = async (refreshToken: string): Promise<WechatTokenResult> => {
  try {
    const response = await axios.get(`https://api.weixin.qq.com/sns/oauth2/access_token?grant_type=refresh_token&appid=${WECHAT_APP_ID}&refresh_token=${refreshToken}`);
    return response.data;
  } catch (error) {
    console.error('刷新微信令牌失败:', error);
    throw new Error('刷新令牌失败');
  }
}; 